package com.github.postsanf.yinian.activity;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.BaseApplication;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.activity.pop.PopListImageDir;
import com.github.postsanf.yinian.adapter.AlbumManageRecyViewAdapter;
import com.github.postsanf.yinian.adapter.LocalManageDayAdapter3;
import com.github.postsanf.yinian.bean.YNFileInfo;
import com.github.postsanf.yinian.bean.YNImageFloder;
import com.github.postsanf.yinian.bean.YNNativeImage;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.ISkinUpdate;
import com.github.postsanf.yinian.constants.SelectedImg;
import com.github.postsanf.yinian.utils.UIHelper;
import com.github.postsanf.yinian.nativestick.StickyGridHeadersGridView;
import com.github.postsanf.yinian.utils.DisplayUtils;
import com.github.postsanf.yinian.utils.ImageUtils;
import com.github.postsanf.yinian.utils.SkinPackageManager;
import com.github.postsanf.yinian.utils.WrapContentLinearLayoutManager;
import com.github.postsanf.yinian.utils.YNNativeComparator;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.io.FileFilter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;


public class LocalTimeCardManageActivity extends BaseActivity implements PopListImageDir.OnImageDirSelected, View.OnClickListener, ISkinUpdate {
    private Toolbar mToolbar;
    private LinearLayout ll_album_title_btn;
    private TextView tv_album_name_show;                // 相册名
    private LocalManageDayAdapter3 mAdapter;                        // 相册适配器
    private PopListImageDir mListImageDirPopupWindow;        // 弹窗相册路径
    private StickyGridHeadersGridView mGirdView;                        // 网格布局
    private ProgressDialog mProgressDialog;                // 进度条
    private int mScreenHeight;                    // 屏高
    private int mPicsSize;                        // 文件夹图片数量
    private File mImgDir;                        // 图片数量最多的文件夹
    private List<String> mfristImgsnew = new ArrayList<>();
    private ImageView iv_btn_expend_switch;
    private RelativeLayout rl_album_manage_bottom;
    private RelativeLayout rl_pop_top;
    private TextView mPreview;                        // 预览
    private ImageView mUpLoad;                            // 上传
    private TextView mComplete;                            // 已完成张数
    private HashSet<String> mDirPaths = new HashSet<String>();
    // 所有的图片文件夹
    private List<YNImageFloder> mImageFloders = new ArrayList<YNImageFloder>();
    private List<YNImageFloder> mImageFlodersnew = new ArrayList<YNImageFloder>();
    private Resources mResource;
    private RecyclerView mamageRecylerView;
    private AlbumManageRecyViewAdapter dAdapter;
    private Map<String, List<YNNativeImage>> dayMap = new HashMap<>();
    private Map<String, List<YNNativeImage>> monMap = new HashMap<>();
    private List<YNNativeImage> mNativeImageList = new ArrayList<>();
    private List<YNNativeImage> mNativeImageListMon = new ArrayList<>();
    private Map<String, Integer> sectionMap = new HashMap<>();
    private static int section = 1;
    private boolean dayTime = true;
    private TextView tv_switch;
    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 0x110:
                    // 为View绑定数据
                    data2View();
                    break;
                case 1:
                    // 初始化展示文件夹的popupWindw
                    initListDirPopupWindw();
                    mAdapter = new LocalManageDayAdapter3(LocalTimeCardManageActivity.this, mNativeImageList, true, dayTime, dayMap, monMap);
                    if (mResource != null) {
                        mAdapter.setResource(mResource);
                    }
                    mGirdView.setAdapter(mAdapter);
                    if (mProgressDialog != null)
                        mProgressDialog.dismiss();
                    break;
            }

        }
    };

    Handler numHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    showToast(getString(R.string.photo_select_tip_start)
                            + UIHelper.MAX_IMG_COUNT
                            + getString(R.string.photo_select_tip_end));
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        registerBoradcastReceiver();
        setContentView(R.layout.yn_activity_local_manage3);
        BaseApplication.getInstance().mActivitys.add(this);
        mScreenHeight = DisplayUtils.getScreenHeightPixels(this);
        initView();
        getImages();
        initEvent();
    }

    private void initView() {
        mToolbar = (Toolbar) findViewById(R.id.local_manage_toolbar);
        setSupportActionBar(mToolbar);
        mToolbar.setNavigationIcon(R.drawable.ic_return);

        mUpLoad = (ImageView) findViewById(R.id.btn_album_manage_sure);
        mComplete = (TextView) findViewById(R.id.btn_album_manage_complete);
        mamageRecylerView = (RecyclerView) findViewById(R.id.album_mamage_recylerview);

        mGirdView = (StickyGridHeadersGridView) findViewById(R.id.gv_album_gridView);
        mGirdView.setAreHeadersSticky(false);
        mPreview = (TextView) findViewById(R.id.btn_album_manage_preview);
        tv_album_name_show = (TextView) findViewById(R.id.tv_album_name_show);
        ll_album_title_btn = (LinearLayout) findViewById(R.id.ll_album_title_btn);
        rl_pop_top = (RelativeLayout) findViewById(R.id.rl_pop_top);
        iv_btn_expend_switch = (ImageView) findViewById(R.id.iv_btn_expend_switch);
        rl_album_manage_bottom = (RelativeLayout) findViewById(R.id.rl_album_manage_bottom);
        tv_switch = ((TextView) findViewById(R.id.tv_switch));
        tv_switch.setOnClickListener(this);

        mUpLoad.setOnClickListener(this);
        mPreview.setOnClickListener(this);

        WrapContentLinearLayoutManager horLayoutManager = new WrapContentLinearLayoutManager(this);
        horLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mamageRecylerView.setLayoutManager(horLayoutManager);
        dAdapter = new AlbumManageRecyViewAdapter(this, SelectedImg.mSelectedImage);
        mamageRecylerView.setHasFixedSize(true);
        mamageRecylerView.setAdapter(dAdapter);
    }

    // 数据绑定
    private void data2View() {
        if (mImgDir == null) {
            showToast("图片没扫描到");
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int j = 0; j < mImageFloders.size(); j++) {
                    mImgDir = new File(mImageFloders.get(j).getDir());
                    File[] files = mImgDir.listFiles(new FileFilter() {
                        @Override
                        public boolean accept(File file) {
                            String filename = file.getName().toLowerCase();
                            if (file.length() > 0 && !filename.contains(".9")) {
                                if (filename.endsWith(".jpg") || filename.endsWith(".png")
                                        || filename.endsWith(".jpeg") || filename.endsWith(".gif"))
                                    return true;
                            }
                            return false;
                        }
                    });
                    if (files != null) {
                        for (int k = 0; k < files.length; k++) {
                            mfristImgsnew.add(files[k].getAbsolutePath());
                        }
                    }
                }
                mNativeImageList.clear();
                mNativeImageListMon.clear();
                for (int i = 0; i < mfristImgsnew.size(); i++) {
                    File file = new File(mfristImgsnew.get(i));
                    if (file.length() > 0) {
                        String imgPath = file.getPath();
                        long imgTime = file.lastModified();
                        Date currentTime = new Date(imgTime);
                        String dateString = new SimpleDateFormat("yyyy-MM-dd").format(currentTime);
                        YNNativeImage mNativeItem = new YNNativeImage(imgPath, dateString);
                        mNativeImageList.add(mNativeItem);
                        if (dayMap.containsKey(dateString)) {
                            List<YNNativeImage> ynNativeImages = dayMap.get(dateString);
                            ynNativeImages.add(mNativeItem);
                        } else {
                            List<YNNativeImage> list = new ArrayList<YNNativeImage>();
                            list.add(mNativeItem);
                            dayMap.put(dateString, list);
                        }
                        String dateStringMon = new SimpleDateFormat("yyyy-MM").format(currentTime);
                        YNNativeImage mNativeItemMon = new YNNativeImage(imgPath, dateStringMon);
                        mNativeImageListMon.add(mNativeItemMon);
                        if (monMap.containsKey(dateStringMon)) {
                            List<YNNativeImage> ynNativeImages = monMap.get(dateStringMon);
                            ynNativeImages.add(mNativeItemMon);
                        } else {
                            List<YNNativeImage> list = new ArrayList<YNNativeImage>();
                            list.add(mNativeItemMon);
                            monMap.put(dateStringMon, list);
                        }
                    }
                }
                Collections.sort(mNativeImageList, new YNNativeComparator());
                for (ListIterator<YNNativeImage> it = mNativeImageList.listIterator(); it.hasNext(); ) {
                    YNNativeImage mNativeItem = it.next();
                    String ym = mNativeItem.getTime();
                    if (!sectionMap.containsKey(ym)) {
                        mNativeItem.setSection(section);
                        sectionMap.put(ym, section);
                        section++;
                    } else {
                        mNativeItem.setSection(sectionMap.get(ym));
                    }
                }
                Collections.sort(mNativeImageListMon, new YNNativeComparator());
                for (ListIterator<YNNativeImage> it = mNativeImageListMon.listIterator(); it.hasNext(); ) {
                    YNNativeImage mNativeItem = it.next();
                    String ym = mNativeItem.getTime();
                    if (!sectionMap.containsKey(ym)) {
                        mNativeItem.setSection(section);
                        sectionMap.put(ym, section);
                        section++;
                    } else {
                        mNativeItem.setSection(sectionMap.get(ym));
                    }
                }
                mHandler.sendEmptyMessage(1);
            }
        }).start();
    }

    private String switchSure(int val) {
        return val == 0 ? "" : "(" + val + ")";
    }

    // 初始化展示文件夹的popupWindw
    private void initListDirPopupWindw() {
        YNImageFloder imageFloder = new YNImageFloder();
        imageFloder.setDir("所有图片");
        imageFloder.setCount(mNativeImageList.size());
        if (mNativeImageList.size() > 0) {
            imageFloder.setFirstImagePath(mNativeImageList.get(0).getPath());
            mImageFlodersnew.add(imageFloder);
        }
        mImageFlodersnew.addAll(mImageFloders);
        mListImageDirPopupWindow = new PopListImageDir(
                ViewGroup.LayoutParams.MATCH_PARENT, (int) (mScreenHeight * 0.7),
                mImageFlodersnew, LayoutInflater.from(getApplicationContext())
                .inflate(R.layout.yn_album_list_dir, null));
        mListImageDirPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                iv_btn_expend_switch.setImageResource(R.drawable.btn_expend);
                // 设置背景颜色变暗
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1.0f;
                getWindow().setAttributes(lp);
            }
        });
        mListImageDirPopupWindow.setOnImageDirSelected(this);
    }

    private void getImages() {
        if (!Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            showToast("暂无外部存储");
            return;
        }
        // 显示进度条
        mProgressDialog = ProgressDialog.show(this, "", CommonConstants.TIP_LOAD_DATA);
        new Thread(new Runnable() {
            @Override
            public void run() {
                String firstImage = null;
                ContentResolver mContentResolver = LocalTimeCardManageActivity.this
                        .getContentResolver();
                Cursor mCursor = mContentResolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null,
                        MediaStore.Images.Media.MIME_TYPE + "=? or "
                                + MediaStore.Images.Media.MIME_TYPE + "=? or " + MediaStore.Images.Media.MIME_TYPE + "=?",
                        new String[]{"image/jpeg", "image/png", "image/gif"},
                        MediaStore.Images.Media.DATE_MODIFIED);
                while (mCursor.moveToNext()) {
                    String path = mCursor.getString(mCursor.getColumnIndex(MediaStore.Images.Media.DATA));
                    if (firstImage == null)
                        firstImage = path;
                    File parentFile = new File(path).getParentFile();
                    if (parentFile == null)
                        continue;
                    String dirPath = parentFile.getAbsolutePath();
                    YNImageFloder imageFloder = null;
                    if (mDirPaths.contains(dirPath)) {
                        continue;
                    } else {
                        mDirPaths.add(dirPath);
                        imageFloder = new YNImageFloder();
                        imageFloder.setDir(dirPath);
                        imageFloder.setFirstImagePath(path);
                    }
                    File[] pics = new File(dirPath).listFiles(new FileFilter() {
                        @Override
                        public boolean accept(File file) {
                            String filename = file.getName().toLowerCase();
                            if (filename.toLowerCase().endsWith(".jpg") || filename.toLowerCase().endsWith(".png")
                                    || filename.toLowerCase().endsWith(".jpeg") || filename.endsWith(".gif"))
                                return true;
                            return false;
                        }
                    });
                    int picSize = (pics != null) ? pics.length : 0;
                    imageFloder.setCount(picSize);
                    mImageFloders.add(imageFloder);
                    if (picSize > mPicsSize) {
                        mPicsSize = picSize;
                        mImgDir = parentFile;
                    }
                }
                mCursor.close();
                mDirPaths = null;
                mHandler.sendEmptyMessage(0x110);
            }
        }).start();
    }

    private void initEvent() {
        // 相册列表触发
        ll_album_title_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                iv_btn_expend_switch.setImageResource(R.drawable.btn_expend_up);
                mListImageDirPopupWindow.showAsDropDown(rl_pop_top, 0, 0);
                // 设置背景颜色变暗
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = .9f;
                getWindow().setAttributes(lp);
            }
        });
    }

    private void printMessage(ExifInterface e) {
        System.out.println("============================" + "\n"
                + e.getAttribute(ExifInterface.TAG_GPS_LATITUDE) + "\n"
                + e.getAttribute(ExifInterface.TAG_GPS_LONGITUDE) + "\n"
                + e.getAttribute(ExifInterface.TAG_MAKE) + "\n"
                + e.getAttribute(ExifInterface.TAG_MODEL) + "\n"
                + e.getAttribute(ExifInterface.TAG_ORIENTATION) + "\n"
                + e.getAttribute(ExifInterface.TAG_DATETIME) + "\n"
                + e.getAttribute(ExifInterface.TAG_GPS_LATITUDE_REF) + "\n"
                + e.getAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF) + "\n"
                + e.getAttribute(ExifInterface.TAG_GPS_PROCESSING_METHOD)
                + "\n" + e.getAttribute(ExifInterface.TAG_IMAGE_LENGTH) + "\n"
                + e.getAttribute(ExifInterface.TAG_IMAGE_WIDTH));
    }

    /**
     * 目前Android SDK定义的Tag有:
     * TAG_DATETIME 时间日期
     * TAG_FLASH 闪光灯
     * TAG_GPS_LATITUDE 纬度
     * TAG_GPS_LATITUDE_REF 纬度参考
     * TAG_GPS_LONGITUDE 经度
     * TAG_GPS_LONGITUDE_REF 经度参考
     * TAG_IMAGE_LENGTH 图片长
     * TAG_IMAGE_WIDTH 图片宽
     * TAG_MAKE 设备制造商
     * TAG_MODEL 设备型号
     * TAG_ORIENTATION 方向
     * TAG_WHITE_BALANCE 白平衡
     */
    @Override
    public void selected(YNImageFloder floder) {
        ArrayList<YNFileInfo> fileList = new ArrayList<>();
        File[] files = null;
        if (floder.getDir().equals("所有图片")) {
            files = new File[mfristImgsnew.size()];
            for (int i = 0; i < mfristImgsnew.size(); i++) {
                files[i] = new File(mfristImgsnew.get(i));
            }
        } else {
            mImgDir = new File(floder.getDir());
            files = mImgDir.listFiles(new FileFilter() {
                @Override
                public boolean accept(File file) {
                    String filename = file.getName().toLowerCase();
                    if (file.length() > 0 && !filename.contains(".9")) {
                        if (filename.endsWith(".jpg") || filename.endsWith(".png")
                                || filename.endsWith(".jpeg") || filename.endsWith(".gif"))
                            return true;
                    }
                    return false;
                }
            });
        }
        mNativeImageList.clear();
        mNativeImageListMon.clear();
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            if (file.length() > 0) {
                String imgPath = file.getPath();
                Date currentTime = new Date(file.lastModified());
                String dateString = new SimpleDateFormat("yyyy-MM-dd").format(currentTime);
                YNNativeImage mNativeItem = new YNNativeImage(imgPath, dateString);
                mNativeImageList.add(mNativeItem);
                String dateString2 = new SimpleDateFormat("yyyy-MM").format(currentTime);
                YNNativeImage mNativeItem2 = new YNNativeImage(imgPath, dateString2);
                mNativeImageListMon.add(mNativeItem2);
            }
        }
        Collections.sort(mNativeImageList, new YNNativeComparator());
        for (ListIterator<YNNativeImage> it = mNativeImageList.listIterator(); it.hasNext(); ) {
            YNNativeImage mNativeItem = it.next();
            String ym = mNativeItem.getTime();
            if (!sectionMap.containsKey(ym)) {
                mNativeItem.setSection(section);
                sectionMap.put(ym, section);
                section++;
            } else {
                mNativeItem.setSection(sectionMap.get(ym));
            }
        }
        Collections.sort(mNativeImageListMon, new YNNativeComparator());
        for (ListIterator<YNNativeImage> it = mNativeImageListMon.listIterator(); it.hasNext(); ) {
            YNNativeImage mNativeItem = it.next();
            String ym = mNativeItem.getTime();
            if (!sectionMap.containsKey(ym)) {
                mNativeItem.setSection(section);
                sectionMap.put(ym, section);
                section++;
            } else {
                mNativeItem.setSection(sectionMap.get(ym));
            }
        }
        if (dayTime) {
            mAdapter.setData(mNativeImageList, dayTime);
        } else {
            mAdapter.setData(mNativeImageListMon, dayTime);
        }
        mAdapter.notifyDataSetChanged();
        tv_album_name_show.setText(floder.getName());
        mListImageDirPopupWindow.dismiss();
    }

    public void setSureCount(int totals) {
        //mComplete.setText(totals == 0 ? "" : totals + "/8");
//        mUpLoad.setText("上传" + switchSure(totals));
//        mPreview.setText("预览" + switchSure(totals));
    }

    @Override
    public void onClick(View v) {
        List<String> list = SelectedImg.mSelectedImage;
        String[] arr = list.toArray(new String[list.size()]);
        switch (v.getId()) {
            case R.id.btn_album_manage_sure:
                if (SelectedImg.mSelectedImage.size() <= 0) {
                    showToast("请选择相片后再上传");
                    return;
                }
                gotoPublish();
                break;
            case R.id.btn_album_manage_preview:
                if (SelectedImg.mSelectedImage.size() <= 0) {
                    showToast("请选择相片后再预览");
                    return;
                }
                Intent toPreview = new Intent(this, PreviewActivity.class);
                startActivity(toPreview);
                break;
            case R.id.tv_switch:
                dayTime = !dayTime;
                if (dayTime) {
                    mGirdView.setNumColumns(3);
                    mAdapter.setData(mNativeImageList, dayTime);
                    mAdapter.notifyDataSetChanged();
                } else {
                    mGirdView.setNumColumns(4);
                    mAdapter.setData(mNativeImageListMon, dayTime);
                    mAdapter.notifyDataSetChanged();
                }
                //滑动过程中点击切换图片布局会出问题，延时调用该方法将界面重新刷新一次
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mAdapter.notifyDataSetChanged();
                    }
                }, 20);
                break;
        }
    }

    public void gotoPublish() {
        if (getIntent() != null && getIntent().getBooleanExtra(TimeCardEditActivity.class.getName(), false)) {
            if (SelectedImg.mSelectedImage.size() == 0) {
                showToast("至少保留一张图片");
                return;
            }
        }
        Intent toPublish = new Intent(this, TimeCardEditActivity.class);
        toPublish.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        toPublish.putExtra(ACTIONs.IstoSync, getIntent().getBooleanExtra(ACTIONs.IstoSync, false));
        startActivity(toPublish);
        sendBroadcast(new Intent(ACTIONs.updataTimeCardEditPic));
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case ImageUtils.REQUEST_CODE_FROM_CAMERA:
                if (resultCode == RESULT_CANCELED) {
                    ImageUtils.deleteImageUri(this, ImageUtils.imageUriFromCamera);
                } else {
                    Uri imageUriCamera = ImageUtils.imageUriFromCamera;
                    SelectedImg.mSelectedImage.add(ImageUtils.getImageAbsolutePath19(this, imageUriCamera));
                    gotoPublish();
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onBackPressed() {
        if (getIntent() != null && getIntent().getBooleanExtra(TimeCardEditActivity.class.getName(), false)) {
            if (SelectedImg.mSelectedImage.size() == 0) {
                showToast("至少保留一张图片");
                return;
            }
        }
        AnimateFirstDisplayListener.displayedImages.clear();
        sendBroadcast(new Intent(ACTIONs.updataTimeCardEditPic));
        String morePic = getIntent().getStringExtra("morePic");
        if (morePic == null || !morePic.equals("morePic")) {
            SelectedImg.mSelectedImage.clear();
        }
        super.onBackPressed();
        // SelectedImg.mSelectedImage.clear();
    }

    /**
     * 图片加载监听事件
     **/
    public static class AnimateFirstDisplayListener extends
            SimpleImageLoadingListener {

        public static final List<String> displayedImages = Collections
                .synchronizedList(new LinkedList<String>());

        @Override
        public void onLoadingComplete(String imageUri, View view,
                                      Bitmap loadedImage) {
            if (loadedImage != null) {
                ImageView imageView = (ImageView) view;
                boolean firstDisplay = !displayedImages.contains(imageUri);
                if (firstDisplay) {
                    displayedImages.add(imageUri); // 将图片uri添加到集合中
                }
            }
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setSureCount(SelectedImg.mSelectedImage.size());
        mAdapter.notifyDataSetChanged();
    }

    // 清除选中并退出
    private void clearAll() {
        SelectedImg.mSelectedImage.clear();
        finish();
    }

    // 广播接收
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case ACTIONs.actionCloseAlbum:
                    int noClear = intent.getExtras().getInt(ACTIONs.aIsClearSelect);
                    if (1 == noClear) {
                        finish();
                    } else {
                        clearAll();
                    }
                    break;
                case ACTIONs.actionUpdateUpNum:
                    setSureCount(SelectedImg.mSelectedImage.size());
                    break;
                case ACTIONs.actionUpdateReCyView:
                    dAdapter.notifyDataSetChanged();
                    if (SelectedImg.mSelectedImage.size() > 0) {
                        mamageRecylerView.setVisibility(View.VISIBLE);
                    } else {
                        mamageRecylerView.setVisibility(View.GONE);
                    }
                    break;
            }
        }
    };

    //注册广播
    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTIONs.actionCloseAlbum);
        myIntentFilter.addAction(ACTIONs.actionUpdateUpNum);
        myIntentFilter.addAction(ACTIONs.actionUpdateReCyView);
        this.registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    @Override
    protected void onDestroy() {
        BaseApplication.getInstance().mActivitys.remove(this);
        AnimateFirstDisplayListener.displayedImages.clear();
        this.unregisterReceiver(mBroadcastReceiver);
        if (mProgressDialog != null)
            mProgressDialog.dismiss();
        super.onDestroy();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_cancel, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                // SelectedImg.mSelectedImage.clear();
                if (getIntent() != null && getIntent().getBooleanExtra(TimeCardEditActivity.class.getName(), false)) {
                    if (SelectedImg.mSelectedImage.size() == 0) {
                        showToast("至少保留一张图片");
                        return true;
                    }
                }
                SelectedImg.mSelectedImage.clear();
                sendBroadcast(new Intent(ACTIONs.updataTimeCardEditPic));
                finish();
                return true;
//            case R.id.action_cancel:
//                // 发消息取消上传
//                new AlertDialog.Builder(LocalTimeCardManageActivity.this).setMessage("确定不要这张语音图集了吗？")
//                        .setPositiveButton(R.string.yn_app_ok, new DialogInterface.OnClickListener() {
//                            public void onClick(DialogInterface dialog, int whichButton) {
//                                Intent mIntent = new Intent(ACTIONs.actionCloseAlbum);
//                                mIntent.putExtra(ACTIONs.aIsClearSelect, 0);
//                                sendBroadcast(mIntent);
//                            }
//                        }).setNegativeButton(R.string.yn_app_cancel, new DialogInterface.OnClickListener() {
//                    public void onClick(DialogInterface dialog, int whichButton) {
//                    }
//                }).show();
//                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void updateTheme() {
        if (mToolbar != null) {
            try {
                mResource = SkinPackageManager.getInstance(this).mResources;
                mToolbar.setNavigationIcon(mResource.getDrawable(mResource.getIdentifier("ic_return", CommonConstants.THEME_DRAWABLE, CommonConstants.THEME_PACKAGE)));
                mToolbar.setBackgroundColor(mResource.getColor(mResource.getIdentifier("yncolor", CommonConstants.THEME_COLOR, CommonConstants.THEME_PACKAGE)));
                mToolbar.setTitleTextColor(mResource.getColor(mResource.getIdentifier("border_color", CommonConstants.THEME_COLOR, CommonConstants.THEME_PACKAGE)));
                tv_album_name_show.setTextColor(mResource.getColor(mResource.getIdentifier("border_color", CommonConstants.THEME_COLOR, CommonConstants.THEME_PACKAGE)));
                rl_album_manage_bottom.setBackgroundColor(mResource.getColor(mResource.getIdentifier("yncolor", CommonConstants.THEME_COLOR, CommonConstants.THEME_PACKAGE)));
//                mUpLoad.setTextColor(mResource.getColor(mResource.getIdentifier("border_color", CommonConstants.THEME_COLOR, CommonConstants.THEME_PACKAGE)));
//                mPreview.setTextColor(mResource.getColor(mResource.getIdentifier("border_color", CommonConstants.THEME_COLOR, CommonConstants.THEME_PACKAGE)));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 友盟统计
    public void onResume() {
        super.onResume();
        sendBroadcast(new Intent(ACTIONs.actionUpdateReCyView));
        if (SkinPackageManager.getInstance(this).mResources != null) {
            updateTheme();
        }
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }
}
